package com.situ.mall.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.situ.mall.base.entity.Member;
import com.situ.mall.base.exception.InfoException;
import com.situ.mall.base.service.IMemberService;
import com.situ.mall.base.util.URLUtil;
import com.situ.mall.base.vo.ResVO;
import com.situ.mall.order.util.SendMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;


/**
 * ClassName: LogController
 * Package: com.situ.mall.controller
 * Description:
 *
 * @Author Darling_达
 * @Create 2023-04-03 16:04
 * @Version 1.0
 */

@Controller
@RequestMapping("/")
public class LogController {

    @Autowired
    private IMemberService memberService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 页面跳转
    @GetMapping(URLUtil.LOGIN)
    public String login() {
        return URLUtil.LOGIN_HTML;
    }

    // 验证用户登录
    @PostMapping(URLUtil.LOGIN)
    @ResponseBody
    public ResVO doLogin(String username, String password) {
        ResVO vo = new ResVO();
        boolean b = memberService.check(username, password);
        if (b) {
            vo.setData("登陆成功！");
        } else {
            throw new InfoException("账号或密码错误，请重新登录！", 500);
        }
        return vo;
    }

    // 验证码发送
    @GetMapping(URLUtil.CODE)
    @ResponseBody
    public void sendMsg(String tel) throws Exception {
        // 判断此手机号是否注册过
        Member m = memberService.getOne(new LambdaQueryWrapper<Member>().eq(Member::getTel, tel));
        if (m != null) {
            throw new InfoException("此手机号已被注册了！", 500);
        }
        String code = SendMsgUtil.createCode();
        redisTemplate.opsForValue().set(URLUtil.REG_CODE + tel, code, 5, TimeUnit.MINUTES);
        SendMsgUtil.sendMsg(tel, code);
    }

}
